package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.upload.config.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.*;

/**
 * @author syf
 * @version 1.0
 * @date 2019/08/01 17:31
 * @Description TODO:
 */
@Service
public class UploadService {
    //文件上传路径
    private static final String IMG_FILE_PATH="E:\\ruanjian\\nginx-1.16.0\\nginx-1.16.0\\html\\brand-img";
    //文件访问路径
    private static final String IMG_URL_OATH="http://image.leyou.com/brand-img/";
    //文件上传类型
    private static final List ALLOW_ING_TYPE= Arrays.asList("image/jpeg","image/bmp","image/jpg");

    @Autowired
    private OSS client;

    @Autowired
    private OSSProperties prop;

    /**
     * 本地上传
     * @param file
     * @return
     */
    public String uploadFileToNginx(MultipartFile file) {
        try {
            //判断文件类型
            if (!ALLOW_ING_TYPE.contains(file.getContentType())){
                throw  new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //可以吧文件变成流，进行格式判断
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read==null){
                throw  new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
            //指定上传文件地址
            File filePath=new File(IMG_FILE_PATH);
            //指定上传文件名字
            String fileName= UUID.randomUUID()+file.getName();
            //上传文件
            file.transferTo(new File(filePath,fileName));
            return IMG_URL_OATH+fileName;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }

    }

    /**
     * 阿里oss签名上传
     * @return
     */
    public Map<String,Object> getSignature() {

        try {
            long expireTime = prop.getExpireTime();
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, prop.getMaxFileSize());
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, prop.getDir());

            String postPolicy = client.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = client.calculatePostSignature(postPolicy);

            Map<String, Object> respMap = new LinkedHashMap<>();
            respMap.put("accessId", prop.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", prop.getDir());
            respMap.put("host", prop.getHost());
            respMap.put("expire", expireEndTime);
            return respMap;
        }catch (Exception e){
            throw new LyException(ExceptionEnum.UPDATE_OPERATION_FAIL);
        }
    }
}
